package be.jabapage.snooker.service.administration.impl;

import java.io.Serializable;

import org.apache.commons.lang.Validate;

import be.jabapage.snooker.service.administration.api.IFormatParser;

public class FormatParser implements IFormatParser, Serializable {

	private static final long serialVersionUID = -7711203405831277620L;
	private final String playerNumberFormat;
	private final String backupPlayerFormat;
	private final String lastNameFormat;
	private final String firstNameFormat;

	public FormatParser(final String playerNumberFormat, final String backupPlayerFormat, final String lastNameFormat, final String firstNameFormat) {
		Validate.notNull(playerNumberFormat);
		Validate.notNull(backupPlayerFormat);
		Validate.notNull(lastNameFormat);
		Validate.notNull(firstNameFormat);
		this.playerNumberFormat = playerNumberFormat;
		this.backupPlayerFormat = backupPlayerFormat;
		this.lastNameFormat = lastNameFormat;
		this.firstNameFormat = firstNameFormat;
	}

	public String parseClubCode(final String playerNumber) {
		checkPlayerNumber(playerNumber);
		return playerNumber.substring(0,4);
	}

	public String parsePlayerCode(final String playerNumber) {
		checkPlayerNumber(playerNumber);
		return playerNumber.substring(5,9);
	}

	public String parseTeamNumber(final String playerNumber) {
		checkPlayerNumber(playerNumber);
		if (isBackupPlayer(playerNumber)) {
			throw new IllegalArgumentException(playerNumber + " is a backup player.  doesn't have a team.");
		}
		String playerCode = parsePlayerCode(playerNumber);
		String teamNumberString = playerCode.substring(0,2);
		int teamNumber = Integer.parseInt(teamNumberString);
		return Integer.toString(teamNumber);
	}

	public boolean isBackupPlayer(final String playerNumber) {
		checkPlayerNumber(playerNumber);
		String playerCode = parsePlayerCode(playerNumber);
		return playerCode.matches(backupPlayerFormat);
	}

	public String parseFirstName(final String name) {
		Validate.notNull(name);
		return "";
	}

	public String parseLastName(final String name) {
		Validate.notNull(name);
		return name;
	}

	private void checkPlayerNumber(final String playerNumber) {
		Validate.notNull(playerNumber);
		if (!playerNumber.matches(playerNumberFormat)) {
			throw new IllegalArgumentException(String.format("The playernumber %s doesn't match the format %s", playerNumber, playerNumberFormat));
		}
	}
}
